package me.yricky.cov_spectrum.ui.content

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
import me.yricky.chart.base.DataRange
import me.yricky.chart.base.Dataset
import me.yricky.chart.content.coordinate.LineChart
import me.yricky.chart.content.coordinate.chartModifier
import me.yricky.chart.content.coordinate.chartTheme
import me.yricky.cov_spectrum.model.beans.DateCountBean
import me.yricky.cov_spectrum.model.beans.QueryCase
import me.yricky.cov_spectrum.model.utils.datePrev
import me.yricky.cov_spectrum.ui.theme.EmptyPage
import me.yricky.cov_spectrum.ui.theme.LoadingPage
import me.yricky.cov_spectrum.viewmodel.CountQueryViewModel

@Composable
fun QueryLineChart(
    modifier: Modifier = Modifier,
    queryCase: QueryCase,
    name:String,
    queryViewModel: CountQueryViewModel,
    onSelect:((Dataset<DateCountBean>,DateCountBean) ->Unit)? = null
){
    val datasets by queryViewModel.get(queryCase).collectAsState()
    datasets.getOrNull()?.takeIf { !it.isEmpty() }?.let {
        val color = MaterialTheme.colors.primary
        Box(modifier = modifier){
            LineChart(
                modifier = Modifier.fillMaxSize(),
                dataSets = it,
                chartModifier = chartModifier{
                    xRangeTrans = {
                        DataRange(
                            datePrev(187L).toEpochDay(),
                            datePrev(7L).toEpochDay()
                        )
                    }
                },
                chartTheme = chartTheme{
                    lineColor = color
                },
                onSelect = onSelect
            )
            Column {
                val counts = it.datasets.flatMap { it.data.map { it.count } }
                Text(text = "total:${counts.reduce { c1, c2 -> c1+c2 }}", fontSize = 10.sp)
                Text(text = "peek:${counts.max()}", fontSize = 10.sp)
            }
        }

    }
    if(datasets == CountQueryViewModel.loading){
        LoadingPage(modifier)
    }else{
        if (datasets.isSuccess && datasets.getOrNull()?.isEmpty() == true){
            EmptyPage(modifier,"No data")
        }else if(datasets.isFailure){
            EmptyPage(modifier.clickable {
                queryViewModel.refresh(queryCase)
            },datasets.exceptionOrNull()?.localizedMessage ?: "Unknown error")
        }
    }

}